package com.bw.zg2.widgit

import android.content.Context
import android.util.AttributeSet
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
/**
 *
 * @ClassName: AutoLoadRecyclerView
 * @Description: 滑动时不加载图片
 * @Author: zhangyanchao
 * @CreateDate: 2024/9/29 16:36 PM
 * @Version: 1.0
 */
class AutoLoadRecyclerView @JvmOverloads constructor(
    context: Context?,
    attrs: AttributeSet? = null,
    defStyle: Int = 0
) : RecyclerView(
    context!!, attrs, defStyle
) {
    init {
        init()
    }

    private fun init() {
        addOnScrollListener(ImageAutoLoadScrollListener())
    }

    //监听滚动来对图片加载进行判断处理
    inner class ImageAutoLoadScrollListener : OnScrollListener() {
        override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
            super.onScrolled(recyclerView, dx, dy)
        }

        override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
            super.onScrollStateChanged(recyclerView, newState)
            when (newState) {
                SCROLL_STATE_IDLE ->                     //当屏幕停止滚动，加载图片
                    try {
                        if (context != null) Glide.with(context).resumeRequests()
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }

                SCROLL_STATE_DRAGGING ->                     //当屏幕滚动且用户使用的触碰或手指还在屏幕上，停止加载图片
                    try {
                        if (context != null) Glide.with(context).pauseRequests()
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }

                SCROLL_STATE_SETTLING ->                     //由于用户的操作，屏幕产生惯性滑动，停止加载图片
                    try {
                        if (context != null) Glide.with(context).pauseRequests()
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
            }
        }
    }
}